/* Freshtel FT-102 driver demo/test program */

#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>

#include "../freshtel_ioctl.h"

#include "test.xpm"
#include "font.xpm"

int main()
{
	int ftfd;
	struct freshtel_screensize ss;
	long int screensize;
	char *fbp;
	int x, y;
	
	ftfd = open("/dev/freshtel0", O_RDWR);
	if(ftfd == -1) {
		perror("Cannot open freshtel device");
		return 1;
	}
	printf("The freshtel device was opened successfully.\n");

	/* Get the screen resolution, in pixels. */
	ioctl(ftfd, FRESHTEL_SCREENSIZE, &ss);
	printf("Screen is %dx%d\n", ss.w, ss.h);
	
	/* Turn on backlight. If we wanted to turn it off, the ioctl argument would be 0 instead of 1. */
	ioctl(ftfd, FRESHTEL_IOCSBACKLIGHT, 1);
	
	/* Ring three times */
	//ioctl(ftfd, FRESHTEL_IOCRING, 3);
	ioctl(ftfd, FRESHTEL_IOCRING, 0);

	/* Map the screen pixels to memory */
	/* Using read() and write() also works, but is not handy */
	screensize = (ss.w*ss.h)/8;
	fbp = (char *)mmap(0, screensize, PROT_READ|PROT_WRITE, MAP_SHARED, ftfd, 0);
	if ((int)fbp == -1) {
		perror("Failed to map framebuffer device to memory");
		return 2;
	}
	printf("The framebuffer device was successfully mapped to memory.\n");
	
	/* Display a picture by writing to the memory-mapped pixels */
	memset(fbp, 0, screensize);
	for(y=0;y<ss.h;y++)
		for(x=0;x<ss.w;x++)
			if(font_xpm[y+3][x] == '+' || font_xpm[y+3][x] == ' ')
				fbp[(y*ss.w+x)/8] |= (0x80 >> (x % 8));
	/* don't forget to update the device's screen, the driver doesn't do
	 * this automatically to save bandwidth -- which completely defeats the
         * purpose of using mmio here. */
	ioctl(ftfd, FRESHTEL_IOCUPDATE, NULL);

	munmap(fbp, screensize);
	close(ftfd);
	return 0;
}
